<?php

class sfJSONActions extends sfActions
{
  /**
   * Return in JSON when requested via AJAX or as plain text when requested directly in debug mode
   *
   */
  public function returnJSON($data)
  {
    if($data instanceof JSONable)
    {
    	$json = $data->getJsonStr();
    	$data = $data->getJsonObj();
    }
    else if(is_array($data) && array_key_exists(0, $data))
    {
    	for($i=0; $i < count($data); $i++)
    	{
    		if($data[$i] instanceof JSONable)
    		{
    			$data[$i] = $data[$i]->getJsonObj();
    		}
    	}
    	$json = json_encode($data);
    }
    else
    {
    	$json = json_encode($data);
    }
    
    if (SF_DEBUG && !$this->getRequest()->isXmlHttpRequest()) 
    {
      sfLoader::loadHelpers('Partial');
      $json = get_partial('global/json', array('data' => $data));
    } 
    else 
    {
      $this->getResponse()->setHttpHeader('Content-type', 'application/json');
    }

    return $this->renderText($json);
  }
}